package nl.boektrust.btsoep.server.wsdl;

import java.util.LinkedList;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Using example from
 * http://code.google.com/intl/nl/appengine/articles/soap.html.
 * 
 * From project dir (with pom.xml) run
 * "mvn org.jvnet.jax-ws-commons:jaxws-maven-plugin:2.1:wsgen"
 * 
 * For now look in target/jaxws/wsgen/wsdl/ for XSD and WSDL, and change the
 * WSDL into soap:address
 * location="http://frans.webhop.org:8080/"+BrowseSoapServlet
 * 
 * @author frans
 * 
 */
@WebService
public class BrowseWsdl {
	private static final Logger logger = LoggerFactory
			.getLogger(BrowseWsdl.class);
	private final List<Book> database = new LinkedList<Book>();

	public BrowseWsdl() {
		// fill with demo data
		for (int i = 1000; i < 2000; i++) {
			Book b = new Book("isbn" + i, "titel" + i, "auteur" + i);
			database.add(b);
		}
	}

	@WebMethod
	public List<Book> searchBooks(Book min, Book max, int offset, int limit) {
		logger.info("searchBooks() input: min=" + min + "; max=" + max
				+ "; offset=" + offset + "; limit=" + limit);
		//store search result:
		List<Book> ret = new LinkedList<Book>();
		//sanitize input:
		min=Book.sanitize(min);
		max=Book.sanitize(max);
		// sql very lite: filter away
		for (Book book : database) {
			boolean add = true;
			add &= (min == null || min.getIsbn() == null || min.getIsbn()
					.compareToIgnoreCase(book.getIsbn()) <= 0);
			add &= (min == null || min.getAuteur() == null || min.getAuteur()
					.compareToIgnoreCase(book.getAuteur()) <= 0);
			add &= (min == null || min.getTitel() == null || min.getTitel()
					.compareToIgnoreCase(book.getTitel()) <= 0);
			add &= (max == null || max.getIsbn() == null || max.getIsbn()
					.compareToIgnoreCase(book.getIsbn()) >= 0);
			add &= (max == null || max.getAuteur() == null || max.getAuteur()
					.compareToIgnoreCase(book.getAuteur()) >= 0);
			add &= (max == null || max.getTitel() == null || max.getTitel()
					.compareToIgnoreCase(book.getTitel()) >= 0);
			if (add) {
				ret.add(book);
			}
		}
		// sort
		// limit, offset
		List<Book> ret2 = new LinkedList<Book>();
		for (int i = 0; i < limit && i + offset<ret.size(); i++) {
			ret2.add(ret.get(i + offset));
		}

		//logger.info("searchBooks() return: ret2=" + ret2);
		return ret2;
	}
}
